Skip to content

Conversation

@AlexWaygood
Copy link
Member

@AlexWaygood AlexWaygood commented Dec 16, 2024

We have some warnings in the docs for typing.runtime_checkable already, but:

  • they're not very prominent
  • I think it's not absolutely clear how the problems described by these notes might cause concrete issues for users

This PR makes the warnings more prominent and expands on the examples. It follows renewed discussion on how runtime-checkable protocols are fundamentally unsafe in many ways on the Discourse thread https://discuss.python.org/t/pep-767-annotating-read-only-attributes/73408


📚 Documentation preview 📚: https://cpython-previews--127985.org.readthedocs.build/

@AlexWaygood
Copy link
Member Author


Runtime-checkable protocols are known to be unsafe in several ways.
Runtime-checkable protocols are known to be unsound in several ways.
You should only use them for simple protocols, and even then only use
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What about suggesting that they should only be used for method-only protocols? Or just for protocols with dunder methods -- since dunder methods typically have a well-understood signature, so the check is more likely to do the right thing at runtime?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It isn't safe on even just dunder methods. An example of this is numpy arrays and __bool__, see other discussion about type checkers making unsafe assumptions related to this here

Copy link
Member

@JelleZijlstra JelleZijlstra left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This looks good but I agree with Jukka that it's probably worth mentioning that runtime-checkable protocols make a bit more sense when only methods are involved.

@hugovk hugovk removed the needs backport to 3.12 only security fixes label Apr 10, 2025
@serhiy-storchaka serhiy-storchaka added the needs backport to 3.14 bugs and security fixes label May 8, 2025
@JelleZijlstra
Copy link
Member

@AlexWaygood this has a conflict now, and some suggested wording changes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

Status: Todo

Development

Successfully merging this pull request may close these issues.

6 participants